<template>
  <div class="addCar">
    <van-nav-bar
      :fixed="true"
      :placeholder="true"
      :title="$route.meta.title"
      left-text="返回"
      left-arrow
      @click-left="onClickLeft"
    />
    <!-- 表单 -->
    <div class="formData">
      <van-form ref="form">
        <div class="title">车辆信息</div>
        <div class="uploadImg">
          <div
            class="delBtn"
            v-if="dataSource.imgUrl"
            @click="dataSource.imgUrl = ''"
          >
            x
          </div>
          <img
            v-if="dataSource.imgUrl"
            class="imgUrl"
            :src="dataSource.imgUrl"
          />
          <van-uploader
            v-else
            :after-read="getDriverCardInformation"
            class="uploadImg_com"
            :max-size="5000 * 1024"
            @oversize="onOversize"
          />
          <!-- <input type="file" class="uploadImg_com" @change="handleFileUpload" /> -->
        </div>
        <div class="imgtxt">上传行驶证自动识别</div>
        <van-field
          v-model="dataSource.fixCenterName"
          required
          name="所属维修中心"
          label="所属维修中心"
          placeholder="请选择"
          input-align="right"
          :rules="[{ required: true }]"
          right-icon="arrow"
          @click="handleSelect('fixCenterId', 'fixCenterName')"
          readonly
        />
        <van-field
          v-model="dataSource.adminOrgName"
          required
          name="所属品牌"
          label="所属品牌"
          placeholder="请选择"
          input-align="right"
          :rules="[{ required: true }]"
          right-icon="arrow"
          @click="handleSelect('adminOrgId', 'adminOrgName')"
          readonly
        />
        <van-field
          v-model="dataSource.showOrgName"
          required
          name="所属展厅"
          label="所属展厅"
          placeholder="请选择"
          input-align="right"
          :rules="[{ required: true }]"
          right-icon="arrow"
          @click="handleSelect('showOrgId', 'showOrgName')"
          readonly
        />
        <van-field
          v-model="dataSource.cartypesName"
          required
          name="车辆来源"
          label="车辆来源"
          input-align="right"
          placeholder="请选择"
          readonly
          :rules="[{ required: true }]"
          right-icon="arrow"
          @click="handleSelect('cartypesId', 'cartypesName')"
        />
        <van-field
          v-model="dataSource.carModelName"
          required
          name="车型"
          label="车型"
          input-align="right"
          placeholder="请选择车型"
          readonly
          :rules="[{ required: true }]"
          right-icon="arrow"
          @click="handleSelect('carModelId', 'carModelName')"
        />

        <van-field
          v-model="dataSource.carNo"
          required
          name="车牌号码"
          label="车牌号码"
          input-align="right"
          placeholder="请输入车牌号码"
          :rules="[{ required: true }]"
        />

        <van-field
          required
          v-model="dataSource.vinNo"
          name="车架号"
          label="车架号"
          input-align="right"
          placeholder="请输入车架号"
          :rules="[{ required: true }]"
        />
        <van-field
          v-model="dataSource.style"
          name="款式（年款）"
          label="款式（年款）"
          input-align="right"
          placeholder="请输入款式"
        />

        <div class="title">客户信息</div>
        <div class="uploadImg">
          <div
            class="delBtn"
            v-if="dataSource.idCardImg"
            @click="dataSource.idCardImg = ''"
          >
            x
          </div>
          <img
            v-if="dataSource.idCardImg"
            class="imgUrl"
            :src="dataSource.idCardImg"
          />
          <van-uploader
            v-else
            :after-read="getIDCardInformation"
            class="uploadImg_com"
          />
          <!-- <input type="file" class="uploadImg_com" @change="handleFileUpload" /> -->
        </div>
        <div class="imgtxt">上传身份证自动识别</div>
        <van-field
          required
          v-model="dataSource.name"
          name="客户姓名"
          label="客户姓名"
          input-align="right"
          :rules="[{ required: true }]"
          placeholder="请输入"
        />

        <van-field
          required
          v-model="dataSource.mobile"
          name="联系电话"
          label="联系电话"
          input-align="right"
          placeholder="请输入"
          :rules="[
            { required: true },
            { pattern: /^1[3456789]\d{9}$/, message: '手机号码格式错误！' },
          ]"
        />

        <van-field
          name="radio"
          required
          label="性别"
          input-align="right"
          :rules="[{ required: true }]"
        >
          <template #input>
            <van-radio-group v-model="dataSource.gender" direction="horizontal">
              <van-radio
                :name="item.value"
                v-for="(item, index) in generList"
                :key="index"
              >
                {{ item.name }}
              </van-radio>
            </van-radio-group>
          </template>
        </van-field>

        <van-field
          v-model="dataSource.IDCardNo"
          name="证件号码"
          label="证件号码"
          input-align="right"
          placeholder="请输入"
        />
        <van-field
          required
          v-model="dataSource.SHCustomerName"
          name="二手车需求"
          label="二手车需求"
          input-align="right"
          placeholder="请输入"
          @click="handleSelect('SHCustomer', 'SHCustomerName')"
          :rules="[{ required: true }]"
          right-icon="arrow"
          readonly
        />
        <!-- 下拉选择弹窗 -->
        <van-popup v-model="showSelectPicker" position="bottom">
          <van-field
            name="模糊查询"
            v-if="likeWhoField == 'fixCenterId' || likeWhoField == 'carModelId'"
            input-align="left"
            v-model="likeWho"
            label="模糊查询"
            placeholder="请输入模糊查询关键词"
          />
          <van-picker
            show-toolbar
            :columns="columns"
            @confirm="handleSelectConfirm"
            @cancel="showSelectPicker = false"
            value-key="name"
          />
        </van-popup>
      </van-form>
      <div class="submitBtn" @click="formOnSubmit">提交</div>
    </div>
    <div class="loading" v-if="loading">
      <van-loading
        size="40px"
        class="loadbox"
        color="#0094ff"
        text-color="#0094ff"
      >
        提交中，请稍等...
      </van-loading>
      <div class="mask"></div>
    </div>
  </div>
</template>

<script>
import {
  Search,
  Empty,
  Field,
  Form,
  Uploader,
  DatetimePicker,
  Notify,
  Loading,
  Toast,
} from "vant";
import commonApi from "@/api/commonApi";
import carApi from "@/api/carApi";
import axios from "axios";
import { getCookies } from "../../utils/util";
export default {
  name: "addCar",
  components: {
    Search,
    Empty,
    Field,
    Form,
    Uploader,
    DatetimePicker,
    Notify,
    Loading,
    Toast,
  },
  data() {
    return {
      showTimerPicker: false,
      dataSource: {
        adminOrgId: "", //品牌id，String，必填
        showOrgId: "", //所属展厅id,必填，String
        cartypesId: "LDrW1UdsS5urH1BfIbQHGdJSPFw=", //车辆来源id,必填，String
        cartypesName: "维修", //车辆来源id,必填，String
        fixCenterId: "", //维修中心ID值,必填，String
        fixCenterName: "",
        carModelId: "", //车型，ID值,必填，String
        carModelName: "",
        style: "", //款式(年限)
        carNo: "", //车牌号码 必填
        vinNo: "", //车架号
        name: "", //客户姓名
        mobile: "", //	联系电话
        rbmale: null, //男
        rbfemale: null, //女
        IDCardNo: "", //证件号码
        SHCustomer: "", //二手车需求
        SHCustomerName: "",
        imgUrl: "",
        idCardImg: "",
        gender: 1,
        // imgUrl:
        // "https://img2.baidu.com/it/u=3329909248,3799019568&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500",
      },
      uploader: [],
      columns: [],
      showSelectPicker: false,
      disabled: false,
      generList: [
        { name: "男", value: 1 },
        { name: "女", value: 2 },
      ],
      userId: getCookies("userId"),
      fixCenterList: [],
      showOrgList: [],
      brandList: [],
      SHCustomerList: [],
      cartypesList: [],
      carModelList: [],
      loading: false,
      billCarId: "",
      driverCardImg: "",
      idCardImg: "",
      likeWhoField: "",
      likeWho: "",
    };
  },

  mounted() {
    this.getMainFixCenter();
    this.getSHCustomer();
    this.getCartypesList();
  },
  watch: {
    likeWho: function (nval, oval) {
      if (this.likeWhoField == "fixCenterId") {
        if (nval) {
          let newArr = this.fixCenterList.filter((item) => {
            return item.name.indexOf(nval) > -1;
          });
          this.columns = newArr;
        } else {
          this.columns = this.fixCenterList;
        }
      }
      if (this.likeWhoField == "carModelId") {
        if (nval) {
          let newArr = this.carModelList.filter((item) => {
            return item.name.indexOf(nval) > -1;
          });
          this.columns = newArr;
        } else {
          this.columns = this.carModelList;
        }
      }

      // v-if="likeWhoField == 'fixCenterId'||likeWhoField=='carModelId'"
    },
  },

  methods: {
    // 获取维修中心
    getMainFixCenter() {
      commonApi
        .getMainFixCenter({
          fixCenterId: "",
          userId: this.userId,
          type: "fixCenter",
        })
        .then((res) => {
          if (res.data) {
            this.fixCenterList = res.data;
            this.fixCenterList.forEach((item) => {
              if (localStorage.getItem("orgId") == item.billId) {
                this.dataSource.fixCenterId = item.billId;
                this.dataSource.fixCenterName = item.name;
                this.dataSource.adminOrgId = item.brandId;
                this.dataSource.adminOrgName = item.brandName;
                this.dataSource.showOrgId = item.showOrgId;
                this.dataSource.showOrgName = item.showOrgName;
                this.getCarModel();
              }
            });
          }
        });
    },
    // 获取品牌
    getBrandByFixCenter() {
      commonApi
        .getBrandByFixCenter({
          fixCenterId: this.dataSource.fixCenterId,
          userId: this.userId,
        })
        .then((res) => {
          if (res.data) {
            this.brandList = res.data;
          }
        });
    },
    // 获取展厅
    getShowOrgByFixCenterId() {
      commonApi
        .getShowOrgByFixCenterId({
          fixCenterId: this.dataSource.fixCenterId,
          userId: this.userId,
        })
        .then((res) => {
          if (res.data) {
            this.showOrgList = res.data;
          }
        });
    },
    // 获取二手车需求
    getSHCustomer() {
      commonApi
        .getEnums({
          key: "SHCustomer",
          userId: this.userId,
        })
        .then((res) => {
          if (res.data) {
            let arr = [];
            res.data &&
              res.data.forEach((item) => {
                arr.push({
                  billId: item.value,
                  name: item.name,
                });
              });
            this.SHCustomerList = arr;
            console.log(this.SHCustomerList);
          }
        });
    },
    // 车辆来源
    getCartypesList() {
      commonApi
        .getBaseCode({
          key: "车辆来源",
          userId: this.userId,
        })
        .then((res) => {
          if (res.data) {
            this.cartypesList = res.data;
          }
        });
    },
    // 选择下拉
    handleSelect(field, fieldName) {
      this.showSelectPicker = true;
      if (field == "repair") {
        this.columns = [
          { name: "是", value: 1 },
          { name: "否", value: 2 },
        ];
      } else if (field == "outUser") {
        this.columns = [
          { name: "服务人员1", value: 1 },
          { name: "服务人员2", value: 2 },
        ];
      }
      if (field == "fixCenterId") {
        this.columns = this.fixCenterList;
      } else if (field == "adminOrgId") {
        this.columns = this.brandList;
      } else if (field == "showOrgId") {
        this.columns = this.showOrgList;
      } else if (field == "SHCustomer") {
        this.columns = this.SHCustomerList;
      } else if (field == "cartypesId") {
        this.columns = this.cartypesList;
      } else if (field == "carModelId") {
        this.columns = this.carModelList;
      }
      this.field = field;
      this.fieldName = fieldName;
      this.likeWhoField = field;
    },

    // 选择下拉确认
    handleSelectConfirm(value, index) {
      this.showSelectPicker = false;
      this.dataSource[this.field] = value.billId;
      this.dataSource[this.fieldName] = value.name;
      if (this.field == "fixCenterId") {
        this.getBrandByFixCenter();
        this.getShowOrgByFixCenterId();
        this.clearBrand();
        this.fixCenterList.forEach((item) => {
          if (item.billId == value.billId) {
            this.dataSource.adminOrgId = item.brandId;
            this.dataSource.adminOrgName = item.brandName;
            this.dataSource.showOrgId = item.showOrgId;
            this.dataSource.showOrgName = item.showOrgName;
            this.getCarModel();
          }
        });
        // this.dataSource.adminOrgId;
      }
      if (this.field == "adminOrgId") {
        this.getCarModel();
      }
      this.likeWho = "";
    },
    clearBrand() {
      this.dataSource.adminOrgId = "";
      this.dataSource.adminOrgName = "";
      this.dataSource.showOrgId = "";
      this.dataSource.showOrgName = "";
    },

    // 提交时间处理
    onConfirm(val, field) {
      let year = val.getFullYear();
      let month = val.getMonth() + 1;
      let day = val.getDate();
      let hour = val.getHours();
      let minute = val.getMinutes();
      // let second = val.getSeconds()
      if (month >= 1 && month <= 9) {
        month = `0${month}`;
      }
      if (day >= 1 && day <= 9) {
        day = `0${day}`;
      }
      if (hour >= 0 && hour <= 9) {
        hour = `0${hour}`;
      }
      if (minute >= 0 && minute <= 9) {
        minute = `0${minute}`;
      }
      // if (second >= 0 && second <= 9) { second = `0${second}` }
      this.dataSource[field] = `${year}-${month}-${day} ${hour}:${minute}:00`;
      this.showTimerPicker = false;
    },

    // 格式化时间
    formatter(type, value) {
      if (type === "year") {
        return `${value}年`;
      } else if (type === "month") {
        return `${value}月`;
      } else if (type === "day") {
        return `${value}日`;
      } else if (type === "hour") {
        return `${value}时`;
      } else if (type === "minute") {
        return `${value}分`;
      } else if (type === "second") {
        return `${value}秒`;
      }
      return value;
    },

    // 车型
    getCarModel() {
      commonApi
        .getCarModel({ adminOrgId: this.dataSource.adminOrgId })
        .then((res) => {
          this.carModelList = res.data;
        });
    },

    getDriverCardInformation(file) {
      const data = new FormData();
      data.append("files", file.file);
      this.driverCardImg = file.file;
      this.dataSource.imgUrl = file.content;
      commonApi
        .getDriverCardInformation({ image: file.content })
        .then((res) => {
          this.dataSource.carNo = res.data.words_result["号牌号码"].words;
          this.dataSource.vinNo = res.data.words_result["车辆识别代号"].words;
        });
    },
    getIDCardInformation(file) {
      const data = new FormData();
      data.append("files", file.file);
      this.dataSource.idCardImg = file.content;
      this.idCardImg = file.file;

      commonApi
        .getIDCardInformation({ image: file.content, type: "front" })
        .then((res) => {
          this.dataSource.name = res.data.words_result["姓名"].words;
          this.dataSource.gender =
            res.data.words_result["性别"].words == "男" ? 1 : 2;
          this.dataSource.IDCardNo =
            res.data.words_result["公民身份号码"].words;
        });
    },

    // handleFileUpload(event) {
    //   console.log(event);
    //   let file = event.target.files[0];
    //   console.log(file);
    //   commonApi.recognizeIDF({ files: file }).then((res) => {});
    // },
    onOversize() {
      Toast("文件大小不能超过 5M");
    },
    uploadFiles() {
      let formData = new FormData();
      formData.append("billId", this.billCarId);
      formData.append("billType", "CarInfo");
      if (this.driverCardImg) {
        formData.append("files", this.driverCardImg);
      }
      if (this.idCardImg) {
        formData.append("files", this.idCardImg);
      }
      commonApi.uploadFiles(formData).then((res) => {
        Notify({ type: "success", message: "添加成功" });
        this.$router.go(-1);
      });
    },

    // 表单提交
    formOnSubmit() {
      this.$refs.form
        .validate()
        .then(() => {
          if (this.dataSource.gender == 1) {
            this.dataSource.rbmale = true;
            this.dataSource.rbfemale = false;
          } else if (this.dataSource.gender == 2) {
            this.dataSource.rbmale = false;
            this.dataSource.rbfemale = true;
          }
          this.loading = true;
          this.dataSource.carNo = this.dataSource.carNo.replace(/\s*/g, "");
          this.dataSource.vinNo = this.dataSource.vinNo.replace(/\s*/g, "");
          carApi
            .addCustomerAndCarInfo({ ...this.dataSource, userId: this.userId })
            .then((res) => {
              console.log(res);
              this.loading = false;
              if (!res.msg) {
                this.billCarId = res.billCarId;
                if (this.driverCardImg || this.idCardImg) {
                  this.uploadFiles();
                } else {
                  Notify({ type: "success", message: "添加成功" });
                  this.$router.go(-1);
                }
              }
            });
        })
        .catch(() => {
          this.loading = false;
          this.$toast.fail("请完善信息");
        });
    },
    onClickLeft() {
      this.$router.go(-1);
    },
  },
};
</script>

<style lang="less" scoped>
@font-face {
  font-family: "iconfont"; /* Project id 4176972 */
  src: url("//at.alicdn.com/t/c/font_4176972_s8s6zd59eop.woff2?t=1689868658391")
      format("woff2"),
    url("//at.alicdn.com/t/c/font_4176972_s8s6zd59eop.woff?t=1689868658391")
      format("woff"),
    url("//at.alicdn.com/t/c/font_4176972_s8s6zd59eop.ttf?t=1689868658391")
      format("truetype");
}

.flex {
  display: flex;
  align-items: center;
}
.title {
  margin: 0 0.3rem;
  font-size: 0.3rem;
  padding-top: 0.3rem;
}
.addCar {
  overflow: hidden;
  background: #fff !important;

  .detail_header {
    justify-content: space-between;
    margin: 0.2rem 0.2rem;
    border-radius: 5px;
    background: #fff;
    padding: 0.3rem;
    .detail_header_lt {
      .carNo {
        font-size: 0.32rem;
        font-weight: bold;
        margin-bottom: 0.2rem;
        .icon-right {
          margin-left: 0.2rem;
          color: #409eff;
        }
      }
      .hank {
        font-size: 0.28rem;
        color: #666;
      }
    }
    .detail_header_rt {
      justify-content: flex-start;
      .txt {
        font-size: 0.28rem;
        color: #161616;
      }
      .icon-tel {
        color: #fff;
        background: #35bc04;
        font-size: 0.32rem;
        padding: 0.1rem;
        border-radius: 50%;
        margin-right: 0.1rem;
      }
    }
  }
  .formData {
    background: #fff;
  }
}

.uploadImg {
  position: relative;
  margin: 0 0.3rem;
  margin-top: 0.3rem;
  height: 3.5rem;
  .delBtn {
    position: absolute;
    right: 10px;
    top: 10px;
    font-size: 0.24rem;
    z-index: 3;
    background: rgba(0, 0, 0, 0.5);
    color: #fff;
    border-radius: 5px;
    text-align: center;
    padding: 0.04rem 0.2rem;
    cursor: pointer;
  }

  .uploadimg_val {
    // position: absolute;
  }
  .imgUrl {
    width: 100%;
    height: 3.5rem;
    display: block;
  }
  .uploadImg_com {
    width: 100%;
    // opacity: 0;
    position: absolute;
    top: 0;
    left: 0;
    height: 3.5rem;
  }
  /deep/.van-field__error-message {
    text-align: right;
  }
  /deep/.van-uploader__input {
    width: 100%;
    height: 3.5rem;
  }
  /deep/.van-uploader__upload {
    width: 100%;
    height: 3.5rem;
    margin: 0;
  }
}
.imgtxt {
  text-align: center;
  color: #999;
  font-size: 0.3rem;
  margin: 0.3rem 0;
}
.submitBtn {
  background: #1174d6;
  text-align: center;
  font-size: 0.3rem;
  padding: 0.3rem 0;
  width: 90%;
  margin: 0.5rem auto;
  color: #fff;
  border-radius: 5px;
}
.loading {
  position: fixed;
  width: 100%;
  height: 100%;
  .loadbox {
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    z-index: 11;
  }
  .mask {
    background: rgba(0, 0, 0, 0.5);
    position: fixed;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    z-index: 10;
  }
}
</style>
